import http from '@ohos.net.http';
import { BusinessError } from '@ohos.base';
import { AppConfig } from '../common/config';
import UserSessionManager from '../common/UserSession';

// ======================================================
// === 类型定义部分 ===
// ======================================================

export interface ApiResponse<T> {
  code: number;
  message: string;
  data: T | null;
}

export interface ApiChatMessage {
  role: 'user' | 'assistant' | 'system';
  content: string;
}

// 新增：ChatCompletionRequest 类型
export interface ChatCompletionRequest {
  messages: ApiChatMessage[];
  model: string;
  temperature: number;
}

export interface AiReplyData {
  reply: string;
  history: ApiChatMessage[];
}

export interface ChatRequestBody {
  message: string;
  history: ApiChatMessage[];
}

// ======================================================
// === ChatAPIFreeService 类定义 ===
// ======================================================

class ChatAPIFreeService {
  private readonly BASE_URL = AppConfig.API_BASE_URL;

  /**
      * 发送聊天消息到Chat API Free服务
      * @param requestBody 包含用户消息和对话历史的请求体
      * @returns 返回一个Promise，包含处理后的AI回复数据
      */
  async sendMessage(requestBody: ChatCompletionRequest): Promise<ApiResponse<AiReplyData>> {
    const httpRequest = http.createHttp();
    // 每次动态拼接 URL
    const url = `${this.BASE_URL}/api/chat/`;
    try {
      const token = await UserSessionManager.getToken();
      console.error('[ChatService] 实际请求URL:', url);

      // ...已有日志...
      console.error('[ChatService] token:', token);
      console.error('[ChatService] 请求header:', JSON.stringify({
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Authorization': token ? `Bearer ${token}` : ''
      }));
      console.error('[ChatService] 请求body:', JSON.stringify(requestBody));

      const response = await new Promise<http.HttpResponse>((resolve, reject) => {
        httpRequest.request(
          url,
          {
            method: http.RequestMethod.POST,
            header: {
              'Content-Type': 'application/json',
              'Accept': 'application/json',
              'Authorization': token ? `Bearer ${token}` : ''
            },
            extraData: JSON.stringify(requestBody),
            connectTimeout: 15000,
            readTimeout: 60000
          },
          (err: BusinessError, data: http.HttpResponse) => {
            if (err) {
              console.error('[ChatService] 请求异常:', err, JSON.stringify(err));
              reject(err)
            } else {
              console.info('[ChatService] 响应状态码:', data.responseCode);
              console.info('[ChatService] 响应内容:', data.result ? data.result.toString() : '');
              resolve(data)
            }
          }
        )
      })
      if (response.responseCode === 200) {
        const result: ApiResponse<AiReplyData> = JSON.parse(response.result.toString())
        return result
      } else {
        return {
          code: response.responseCode,
          message: `API请求失败: HTTP ${response.responseCode}`,
          data: null
        };
      }
    } catch (error) {
      console.error('[ChatService] 捕获异常:', JSON.stringify(error));
      return {
        code: 500,
        message: '服务暂时不可用，请稍后重试',
        data: null
      };
    } finally {
      httpRequest.destroy();
    }
  }
}

// 导出一个单例
export const chatService = new ChatAPIFreeService();
